from django.http import HttpResponse
import cpca
from . import models
import pkuseg
import pandas as pd

street_dict_set = models.BsStreet.objects.values_list('street_name', flat=True)
street_dict = list(street_dict_set)


def address_standardization(request):
    """
    地址处理的入口，与接口进行映射
    :param request: 前端发来的请求，携带地址参数
    :return: 标准化的地址，json格式
    """
    original_address = request.GET.get('original_address')
    address_tmp = cpca.transform([original_address]).loc[0]
    address_detail_list = address_standardization_street(address_tmp['地址'])
    province = address_tmp['省']
    city = address_tmp['市']
    county = address_tmp['区']
    adcode = address_tmp['adcode']
    street = address_detail_list[0]
    detail = address_detail_list[1]
    result_list = [province, city, county, adcode, street, detail]
    result_df = pd.DataFrame([result_list], columns=['province', 'city', 'county', 'adcode', 'street', 'detail'])
    result = result_df.to_json(orient="records", lines=True, force_ascii=False)
    return HttpResponse(result)


def address_standardization_street(address_detail):
    """
    提取含有乡、镇、街道的地址
    :param address_detail: cpca处理之后的详细地址
    :return: 街道
    """
    result_list = []
    street = ''
    model = pkuseg.pkuseg(user_dict=street_dict, postag=False)
    participle = model.cut(address_detail)
    i = 1
    for ele in participle:
        i = i + 1
        if i >= 3:
            break
        if (ele in street_dict) & (ele != '街道'):
            street = ele
            participle.remove(street)
            break
        else:
            street = None
    detail = ''.join(participle)
    result_list.append(street)
    result_list.append(detail)
    return result_list
